<template>
  <div v-loading="loading">
    <el-card style="margin: 10px">
      <div slot="header" class="cardHeader">
        <span class="cardTitle">租车合同</span>
        <div>
          <!-- 开启了电子合同 -->
          <template v-if="electronicContractEnable == 1">
            <!-- 已经存在合同  -->
            <template v-if="rentContractUrl">
              <!--  电子合同  -->
              <template v-if="rentContractInfo.contractSource == 2">
                <el-button v-if="rentContractInfo.contractStatus == 1" type="primary"
                  @click="handleContractOpertion(rentContractInfo, 3, 1)">出租方补签</el-button>
                <el-button v-if="rentContractInfo.contractStatus == 2" type="primary"
                  @click="handleContractOpertion(rentContractInfo, 4, 1)">承租方补签</el-button>
                <el-button v-if="(rentContractInfo.contractStatus <= 2)" type="info"
                  @click="handleContractOpertion(rentContractInfo, 5, 1)">废弃</el-button>
              </template>
              <!-- 纸质合同-->
              <template v-else>
                <el-button type="primary" @click="handleContractOpertion(rentContractInfo, 1, 1)">上传合同</el-button>
              </template>
            </template>
            <!--不存在合同-->
            <template v-else>
              <el-button type="primary" @click="handleContractOpertion(rentContractInfo, 1, 1)">上传合同</el-button>
              <el-button type="primary" @click="handleContractOpertion(rentContractInfo, 2, 1)">发起合同</el-button>
            </template>
          </template>

          <!-- 未开启电子合同 -->
          <template v-else>
            <el-button type="primary" @click="handleContractOpertion(rentContractInfo, 1, 1)">上传合同</el-button>
          </template>
        </div>
      </div>

      <div>
        <template v-if="rentContractUrl">
          <template v-if="electronicContractEnable == 1">
            <el-descriptions :column="4">
              <el-descriptions-item label="合同编号">
                {{ rentContractInfo.contractNo }}
              </el-descriptions-item>
              <el-descriptions-item label="出租方签署">
                <template>
                  <span>{{ orderDetail.orderInfo.authenticationName || '--' }}</span>
                  <span style="margin-left: 10px;color: #0d65eb" v-if="orderDetail.orderInfo.authenticationName == null"
                    @click="goCompanyAuth">企业认证</span>
                </template>
              </el-descriptions-item>
              <el-descriptions-item label="承租方签署">
                <template>
                  <div>
                    <span>{{ orderDetail.customerInfo.memberName || '--' }}</span>
                    <span style="margin-left: 10px;color: #0d65eb"
                      v-if="orderDetail.customerInfo.authenticationStatus == 1 || orderDetail.customerInfo.authenticationStatus == 3"
                      @click="sendAuthentication">认证</span>
                  </div>
                </template>
              </el-descriptions-item>
              <el-descriptions-item label="合同状态">
                {{ rentContractInfo.contractStatus | contractStatus }}
              </el-descriptions-item>
            </el-descriptions>
          </template>
          <iframe :src="rentContractUrl" frameborder="1" width="100%" height="600"></iframe>
        </template>
        <template v-else>
          <template v-if="electronicContractEnable == 1">
            <el-descriptions :column="4">
              <el-descriptions-item label="合同编号">
                --
              </el-descriptions-item>
              <el-descriptions-item label="出租方签署">
                <template>
                  <span>{{ orderDetail.orderInfo.authenticationName || '--' }}</span>
                  <span style="margin-left: 10px;color: #0d65eb" v-if="orderDetail.orderInfo.authenticationName == null"
                    type="text" @click="goCompanyAuth">企业认证</span>
                </template>
              </el-descriptions-item>
              <el-descriptions-item label="承租方签署">
                <div>
                  <span>{{ orderDetail.customerInfo.memberName || '--' }}</span>
                  <span style="margin-left: 10px;color: #0d65eb"
                    v-if="orderDetail.customerInfo.authenticationStatus == 1 || orderDetail.customerInfo.authenticationStatus == 3"
                    @click="sendAuthentication">认证</span>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="合同状态">
                --
              </el-descriptions-item>
            </el-descriptions>
          </template>

          <el-empty description="暂无租车合同"></el-empty>
        </template>
      </div>


    </el-card>


    <template v-if="releteContractList && releteContractList.length > 0">
      <el-card style="margin: 10px" v-for="(item, index) in releteContractList" :key="item.reletId">
        <div slot="header" class="cardHeader">
          <span class="cardTitle">续租合同 ( 编号:{{ item.reletId }})</span>
          <div>
            <!-- 开启了电子合同 -->
            <template v-if="electronicContractEnable == 1">
              <!-- 已经存在合同  -->
              <template v-if="item.rentContractUrl">
                <!--  电子合同  -->
                <template v-if="item.contractSource == 2">
                  <el-button v-if="item.contractStatus == 1" type="primary"
                    @click="handleContractOpertion(item, 3, 2)">出租方补签</el-button>
                  <el-button v-if="item.contractStatus == 2" type="primary"
                    @click="handleContractOpertion(item, 4, 2)">承租方补签</el-button>
                  <el-button v-if="(item.contractStatus <= 2)" type="info"
                    @click="handleContractOpertion(item, 5, 2)">废弃</el-button>
                </template>
                <!-- 纸质合同-->
                <template v-else>
                  <el-button type="primary" @click="handleContractOpertion(item, 1, 2)">上传合同</el-button>
                </template>
              </template>
              <!--不存在合同-->
              <template v-else>
                <el-button type="primary" @click="handleContractOpertion(item, 1, 2)">上传合同</el-button>
                <el-button type="primary" @click="handleContractOpertion(item, 2, 2)">发起合同</el-button>
              </template>
            </template>

            <!-- 未开启电子合同 -->
            <template v-else>
              <el-button type="primary" @click="handleContractOpertion(item, 1, 2)">上传合同</el-button>
            </template>
          </div>
        </div>

        <div>
          <template v-if="item.rentContractUrl">
            <template v-if="electronicContractEnable == 1">
              <el-descriptions :column="4">
                <el-descriptions-item label="合同编号">
                  {{ item.contractNo }}
                </el-descriptions-item>
                <el-descriptions-item label="出租方签署">
                  <template>
                    <span>{{ orderDetail.orderInfo.authenticationName || '--' }}</span>
                    <span style="margin-left: 10px;color: #0d65eb"
                      v-if="orderDetail.orderInfo.authenticationName == null" @click="goCompanyAuth">企业认证</span>
                  </template>
                </el-descriptions-item>
                <el-descriptions-item label="承租方签署">
                  <template>
                    <div>
                      <span>{{ orderDetail.customerInfo.memberName || '--' }}</span>
                      <span style="margin-left: 10px;color: #0d65eb"
                        v-if="orderDetail.customerInfo.authenticationStatus == 1 || orderDetail.customerInfo.authenticationStatus == 3"
                        @click="sendAuthentication">认证</span>
                    </div>
                  </template>
                </el-descriptions-item>
                <el-descriptions-item label="合同状态">
                  {{ item.contractStatus | contractStatus }}
                </el-descriptions-item>
              </el-descriptions>
            </template>
            <iframe :src="item.rentContractUrl" frameborder="1" width="100%" height="600"></iframe>
          </template>
          <template v-else>
            <template v-if="electronicContractEnable == 1">
              <el-descriptions :column="4">
                <el-descriptions-item label="合同编号">
                  --
                </el-descriptions-item>
                <el-descriptions-item label="出租方签署">
                  <template>
                    <span>{{ orderDetail.orderInfo.authenticationName || '--' }}</span>
                    <span style="margin-left: 10px;color: #0d65eb"
                      v-if="orderDetail.orderInfo.authenticationName == null" type="text"
                      @click="goCompanyAuth">企业认证</span>
                  </template>
                </el-descriptions-item>
                <el-descriptions-item label="承租方签署">
                  <div>
                    <span>{{ orderDetail.customerInfo.memberName || '--' }}</span>
                    <span style="margin-left: 10px;color: #0d65eb"
                      v-if="orderDetail.customerInfo.authenticationStatus != 2 || orderDetail.customerInfo.authenticationStatus != 4"
                      @click="sendAuthentication">认证</span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="合同状态">
                  --
                </el-descriptions-item>
              </el-descriptions>
            </template>

            <el-empty description="暂无续租合同"></el-empty>
          </template>
        </div>


      </el-card>
    </template>


    <!-- 上传合同确定弹框 -->
    <el-dialog title="选择合同附件" :visible.sync="dialogVisibleFile" append-to-body width="30%">
      <contract-upload is-show-tip button-title="选择文件" @uploadSuccess="uploadSuccess"></contract-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleFile = false">取 消</el-button>
        <el-button type="primary" @click="makeSureUpdate()">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import * as contractApi from "@/api/contract/contract";
import ContractUpload from "@/components/FileUpload/contractUpload.vue"
import { addContract, uploadContract } from "@/api/contract/contract";
import { illegalQueryPriceDetail } from "@/api/credit/credit";
import { memberCertification } from "@/api/customer/customer";

export default {
  components: {
    ContractUpload
  },
  props: {
    orderNo: {
      type: String | Number,
      default: ''
    },
    orderDetail: {
      type: Object,
      default() {
        return {
          customerInfo: {},
          orderInfo: {}
        }
      }
    }
  },
  data() {
    // 这里存放数据
    return {
      loading: false,
      //微软在线预览链接 支持word, excel, ppt(有微软的标识,支持下载及打印)
      baseUrl: 'https://view.officeapps.live.com/op/view.aspx?src=' + process.env.VUE_APP_BASE_IMAGE_URL,
      pdfUrl: process.env.VUE_APP_BASE_IMAGE_URL,
      //XDOC文档预览(云连接, 只支持预览,不支持下载及打印)
      // baseUrl : 'http://view.xdocin.com/xdoc?_xdoc=' +  process.env.VUE_APP_BASE_IMAGE_URL,
      //谷歌在线预览(必须使用代理否则无法使用)
      // baseUrl : 'https://docs.google.com/viewer?url=' +  process.env.VUE_APP_BASE_IMAGE_URL,
      dialogVisibleFile: false,
      // 是否开通了电子合同 0否 1是
      electronicContractEnable: 1,
      rentContractInfo: {
        businessType: 1,
        contractFileAddress: null,
        urlDoc: null

      },
      releteContractList: [],
      uploadParams: {
        orderNo: this.orderNo,
        businessType: 1,
        contractFileAddress: '',
        reletId: null
      }
    }
  },
  computed: {
    tenantId() {
      return this.$store.state.user.tenantId;
    },
    rentContractUrl() {
      let rentContractUrl = null;
      if (this.rentContractInfo.contractSource) {
        const contractFileAddress = this.rentContractInfo.contractFileAddress;
        let containerStr = new RegExp("https");
        const isHttp = containerStr.test(contractFileAddress);
        if (isHttp) {
          rentContractUrl = contractFileAddress;
        } else {
          const sourceUrl = this.rentContractInfo.contractSource == 2 ? this.pdfUrl : this.baseUrl;
          rentContractUrl = sourceUrl + encodeURIComponent(this.rentContractInfo.contractFileAddress);
        }
      }
      return rentContractUrl;
    }
  },
  // 方法集合
  methods: {
    // 企业认证
    goCompanyAuth() {
      this.$router.push({ path: '/enterpriseCertification/add' })
    },

    //客户发起认证
    sendAuthentication(row) {
      this.$alert('确定发起认证吗?', '发起认证', {
        confirmButtonText: '确定',
        callback: action => {
          if (action == 'confirm') {
            memberCertification(this.orderDetail.customerInfo.memberNo).then(res => {
              this.$message({
                type: 'success',
                message: '发起成功'
              });
            })
          }
        }
      });
    },

    /*上传合同的成功回调*/
    uploadSuccess(fileInfo) {
      this.uploadParams.contractFileAddress = fileInfo.fileName;
    },

    /*获取合同信息*/
    getOrderContract() {
      this.loading = true;
      contractApi.orderContract(this.orderNo).then(res => {
        this.loading = false;
        const data = res.data;
        this.rentContractInfo = {};
        this.releteContractList = [];
        if (data.carRental) {
          this.rentContractInfo = data.carRental;
        }
        this.releteContractList = data.renewal || [];
        if (this.releteContractList.length > 0) {
          this.releteContractList = this.releteContractList.map(item => {
            let rentContractUrl = null;
            if (item.contractSource) {
              const contractFileAddress = item.contractFileAddress;
              let containerStr = new RegExp("https");
              const isHttp = containerStr.test(contractFileAddress);
              if (isHttp) {
                rentContractUrl = contractFileAddress
              } else {
                const sourceUrl = item.contractSource == 2 ? this.pdfUrl : this.baseUrl;
                rentContractUrl = sourceUrl + encodeURIComponent(item.contractFileAddress);
              }
            }
            this.$set(item, 'rentContractUrl', rentContractUrl);
            return item;
          })
        }
      })
    },

    /*操作*/
    handleContractOpertion(contractInfo, type, businessType) {
      switch (type) {
        case 1: //上传合同
          this.dialogVisibleFile = true;
          this.uploadParams.orderNo = this.orderNo;
          this.uploadParams.businessType = businessType;
          this.uploadParams.reletId = contractInfo.reletId;
          break
        case 2://发起合同
          this.createContract(contractInfo, businessType);
          break
        case 3://出租方签署
          this.updateContractStatus(contractInfo, 1, '确定发起合同签署吗?')
          break
        case 4://承租方签署
          this.updateContractStatus(contractInfo, 2, '确定发起合同签署吗?')
          break
        case 5://废弃
          this.updateContractStatus(contractInfo, 0, '确定废弃合同吗?')
          break
        default:
          break
      }
    },
    /*发起合同*/
    createContract(contractInfo, businessType) {
      this.$confirm('确定发起合同签署吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        contractApi.addContract({
          memberNo: this.orderDetail.customerInfo.memberNo,
          takeStoreId: this.orderDetail.orderInfo.takeStoreId,
          orderNo: this.orderNo,
          businessType: businessType,
          reletId: contractInfo.reletId
        }).then(res => {
          this.$message({
            type: 'success',
            message: '发起成功'
          })
          this.getOrderContract();
        })
      })
    },


    /*更新合同状态*/
    updateContractStatus(contractInfo, status, alertMsg) {
      this.$confirm(alertMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        contractApi.updateContractStatus({
          id: contractInfo.id,
          contractStatus: status
        }).then(res => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.getOrderContract();
        })
      })
    },
    /*确定上传合同*/
    makeSureUpdate() {
      this.dialogVisibleFile = false;
      contractApi.uploadContract(this.uploadParams).then(res => {
        this.getOrderContract();
      })
    },
    /*获取租户信息*/
    getTenantInfo() {
      illegalQueryPriceDetail(this.tenantId).then(res => {
        this.electronicContractEnable = res.data?.electronicContractEnable || 0;
      })
    }

  },
  // 生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {
    this.getOrderContract();
    this.getTenantInfo();
  },

}
</script>

<style lang="scss" scoped>
.cardBox {}

.cardHeader {
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  .cardTitle {
    color: #333333;
    font-weight: bold;
    font-size: 16px;

    &::before {
      display: inline-block;
      content: '';
      width: 10px;
      height: 10px;
      border-radius: 5px;
      background-color: #5473E8;
      margin-right: 4px;
    }
  }

}
</style>
